package org.jks.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.exception.ConstraintViolationException;
import org.jks.model.Privilege;
import org.jks.model.Role;
import org.jks.model.RolePrivilege;
import org.jks.model.User;
import org.jks.request.model.Ids;
import org.jks.request.model.UIPrivilege;
import org.jks.response.model.ActionResult;
import org.jks.response.model.UITable;
import org.jks.service.PrivilegeService;
import org.jks.service.RoleService;
import org.jks.service.UserService;
import org.jks.util.PrivilegeUtil;
import org.jks.util.ResponseUtil;
import org.jks.util.RoleUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/role")
public class RoleController {
	@Autowired
	RoleService roleService;

	@Autowired
	PrivilegeService privilegeService;
	
	@Autowired
	UserService userService;
	
	@RequestMapping("/add")
	public void add(UIPrivilege uiPrivilege, HttpServletRequest request,
			HttpServletResponse response) 
	{
		ActionResult ar = new ActionResult();
		try {
			Role role = new Role();
			role.setName(uiPrivilege.getName());
			role.setDesp(uiPrivilege.getDesp());
			List<Privilege> privileges = privilegeService.all();
			if(privileges != null){
				List<RolePrivilege> rolePrivileges = new ArrayList<RolePrivilege>();
				for(Privilege privilege: privileges){
					RolePrivilege rolePrivilege = new RolePrivilege();
					rolePrivilege.setRole(role);
					rolePrivilege.setPrivilege(privilege);
					if(PrivilegeUtil.exist(privilege, uiPrivilege.getPrivileges())){
						rolePrivilege.setSelected(true);
					}
					rolePrivileges.add(rolePrivilege);
				}
				role.setPrivileges(rolePrivileges);		
				roleService.save(role);
				ar.setSuccess(true);
			}
			
		}
		catch( ConstraintViolationException e){
			ar.setMsg("角色名称冲突");
		}
		catch (Exception e) {
			ar.setMsg("添加角色失败");
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/delete")
	public void delete(Ids ids, HttpServletRequest request, HttpServletResponse response){
		ActionResult ar = new ActionResult();
		if(RoleUtil.canDelete(ids)){
			try
			{
				List<User> users = userService.all();
				boolean isUsed = false;
				for(User user : users)
				{
					Set<Role> roles = user.getRoles();
					if(roles.size() != 0)
					{
						for(Role r : roles)
						{
							r.setPrivileges(null);
							r.setUsers(null);
							
							for(long id : ids.getIds())
							{
								if(id == r.getId())
								{
									isUsed = true;
									break;
								}
							}
						}
					}
				}
				if(isUsed)
				{
					ar.setMsg("不可以删除!(有用户在使用)");
				}
				else
				{
					for(long id: ids.getIds())
					{
						roleService.delete(id);
					}
					ar.setSuccess(true);
				}
				
			}
			catch(Exception e){
				ar.setMsg("不可以删除!(有用户在使用)");
			}
		}
		else{
			ar.setMsg("系统默认角色不能删除");
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/delete/{id}")
	public void delete(@PathVariable long id, HttpServletRequest request, HttpServletResponse response){
		ActionResult ar = new ActionResult();
		if(RoleUtil.canDelete(id)){
			try{
				roleService.delete(id);
				ar.setSuccess(true);
			}
			catch(Exception e){
				ar.setMsg("不可以删除!(有用户在使用)");
			}
		}
		else{
			ar.setMsg("系统默认角色不能删除");
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/update")
	public void update(Ids ids, Role role, HttpServletRequest request, HttpServletResponse response){
		ActionResult ar = new ActionResult();
		
		List<Privilege> tempList = privilegeService.findPrivilegesByIds(ids.getIds());
		if(tempList == null)
		{
			ar.setSuccess(false);
		}
		else 
		{
			List<Privilege> prList = new ArrayList<Privilege>();
			prList.addAll(tempList);
			//role.setPrivileges(prList);
			roleService.update(role);
			ar.setSuccess(true);
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/all")
	public void all(HttpServletRequest request, HttpServletResponse response){
		ActionResult ar = new ActionResult();
		try{
			List<Role> roles = roleService.all();
			for(Role role: roles){
				List<RolePrivilege> privs = new ArrayList<RolePrivilege>();
				for(RolePrivilege priv : role.getPrivileges()){
					if(priv.getPrivilege().getId() <= 26){
						privs.add(priv);
					}
				}
				role.getPrivileges().removeAll(privs);
			}
			ar.setSuccess(true);
			UITable table = new UITable();
			table.setRows(roles);
			ar.setData(table);
		}
		catch(Exception e){
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/update_priv")
	public void updatePrivilege( UIPrivilege uiPrivilege, HttpServletRequest request, HttpServletResponse response){
		ActionResult ar = new ActionResult();
		try{
			Role role = roleService.findById(uiPrivilege.getRoleId());
			List<RolePrivilege> privileges = role.getPrivileges();
			for(RolePrivilege priv: privileges){
				if(PrivilegeUtil.exist(priv.getPrivilege(), uiPrivilege.getPrivileges())){
					priv.setSelected(true);
				}
				else{
					priv.setSelected(false);
				}
			}
			roleService.update(role);
			ar.setSuccess(true);
		}
		catch(Exception e){
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}
}
